<template>
    <div ref="parentRef" class="watermark_container">
        <slot></slot>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watchEffect } from 'vue';
import useWatermarkBg from './useWatermarkBg.js'
const props = defineProps({
    show:{
        type:Boolean,
        required:false,
        default:false
    },
     text:{
        type:String,
        required:true,
        default:"watermark"
     },
     fontSize:{
        type:Number,
        default:20
     },
     gap:{//间隙
        type:Number,
        default:80
     }
})
const bg = useWatermarkBg(props)
const parentRef = ref(null)
const flag = ref(0)
let ob,div;
watchEffect(()=>{
    flag.value
    if(!parentRef.value){
        return
    }
    if(div){
        div.remove() 
    }
    const {base64,styleSize} = bg.value
    div = document.createElement('div')

    div.style.backgroundImage = `url(${base64})`
    div.style.backgroundSize = `${styleSize}px ${styleSize}px`
    div.style.backgroundRepeat = 'repeat'
    div.style.width = '100%'
    div.style.height = '100%'
    div.style.zIndex = '999'
    div.style.position = 'absolute'
    div.style.inset = '0'
    div.style.pointerEvents='none'
    if(props.show){
        parentRef.value.appendChild(div)
    }
})

onMounted(()=>{
    ob = new MutationObserver((records)=>{
        for (const record of records) {
            // 删除水印
            for (const dom of record.removedNodes) {
                if(dom === div ){
                    flag.value++
                    return
                }
            }
            // 修改
            if(record.target === div){
                flag.value++
                return
            }
        }
    })
    ob.observe(parentRef.value,{
        childList:true,
        attributes:true,
        subtree:true
    })
})
onUnmounted(()=>{
    ob && ob.disconnect()
     div = null
})


</script>

<style lang='scss' scoped>
.watermark_container{
    position: relative;
}
</style>